package org.jsola.hr.service.impl;

import com.alibaba.excel.util.CollectionUtils;
import org.apache.shiro.util.StringUtils;
import org.jsola.admin.entity.SiteDO;
import org.jsola.core.Page;
import org.jsola.hr.provider.IAdminProviderService;
import org.jsola.hr.provider.ILogProviderService;
import org.jsola.hr.service.IHrServiceLogService;
import org.jsola.log.query.ServiceLogQuery;
import org.jsola.log.vo.ServiceLogListVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 服务日志
 *
 * @author june
 */
@Service("hrHrServiceLogServiceImpl")
public class HrServiceLogServiceImpl implements IHrServiceLogService {


    @Autowired
    private ILogProviderService logProviderService;

    @Autowired
    private IAdminProviderService adminProviderService;

    @Override
    public Page<ServiceLogListVO> selectPage(ServiceLogQuery serviceLogQuery, String siteId) {
        Map<String, SiteDO> siteMap = adminProviderService.selectSiteMap();
        if (StringUtils.hasLength(serviceLogQuery.getSiteName())) {
            List<String> siteIds = siteMap.values().parallelStream().map(siteDO -> {
                if (siteDO.getName() != null && siteDO.getName().contains(serviceLogQuery.getSiteName())) {
                    return siteDO.getId();
                }
                return null;
            }).filter(Objects::nonNull).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(siteIds)) {
                return new Page<>(serviceLogQuery.getPageSize(), serviceLogQuery.getPageNo());
            }
            serviceLogQuery.setSiteIds(siteIds);
        }
        Page<ServiceLogListVO> serviceLogListVoPage;
        if (siteId == null) {
            serviceLogListVoPage = logProviderService.selectServiceLogPageNotSiteId(serviceLogQuery);
        } else {
            serviceLogListVoPage = logProviderService.selectServiceLogPage(serviceLogQuery, siteId);
        }
        List<ServiceLogListVO> serviceLogListVOList = serviceLogListVoPage.getEntities();
        if (CollectionUtils.isEmpty(serviceLogListVOList)) {
            return serviceLogListVoPage;
        }
        serviceLogListVOList.parallelStream().forEach(serviceLogListVO -> {
            //组装租户名
            SiteDO siteDO = siteMap.get(serviceLogListVO.getSiteId());
            if (siteDO != null) {
                serviceLogListVO.setSiteName(siteDO.getName());
            }
        });
        return serviceLogListVoPage;
    }
}




